package com.coin900.coin.service.coin;

import com.coin900.coin.base.CoinConstants;
import com.coin900.coin.persist.coin.CoinOrderVO;
import com.coin900.coin.persist.coin.CoinUserProjectVO;
import com.coin900.coin.persist.fu.FuUserWalletVO;
import com.coin900.coin.service.fu.IFuUserWalletService;
import com.value.mybatis.IDaoRouter;
import com.value.mybatis.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单
 *
 * @author shui
 * @create 2018-1-14
 */
@Service
public class CoinOrderService implements ICoinOrderService {

    @Override
    public List<CoinOrderVO> loadCoinOrder(Map<String, Object> params) {
        return this.daoRouter.query("CoinOrder.loadCoinOrder", params);
    }

    @Override
    public List<CoinOrderVO> loadCoinOrderForPage(Pagination pagination) {
        return this.daoRouter.query("CoinOrder.loadCoinOrderForPage", pagination);
    }

    @Override
    public void insertCoinOrder(CoinOrderVO coinOrderVO) {
        // 订单状态未支付
        coinOrderVO.setOrderStatus(CoinConstants.COIN_ORDER_STATUS_NOT_PAID);
        // 生成订单编号
        Date createdDate = coinOrderVO.getCreatedDate();
        SimpleDateFormat format = new SimpleDateFormat("YYMMddHHmmss");
        String formatDate = format.format(createdDate);
        String userId = coinOrderVO.getUserId().toString();
        if (userId.length() >= 4) {
            userId = userId.substring(userId.length() - 4, userId.length());
        } else {
            userId = String.format("%04d", coinOrderVO.getUserId());
        }
        String orderNo = formatDate + userId + (int) (Math.random() * 9000 + 1000);
        coinOrderVO.setOrderNo(orderNo);
        this.daoRouter.insert("CoinOrder.insertCoinOrder", coinOrderVO);
    }

    @Override
    public void updateCoinOrder(CoinOrderVO coinOrderVO) {
        this.daoRouter.update("CoinOrder.updateCoinOrder", coinOrderVO);
    }

    /**
     * 订单分成两类，type=1 正在进行中的项目 2 预售项目
     * 正在进行中的项目订单 - 直接扣款 - 扣 balance - 加 token
     * 预售项目 - 锁定金额 - 扣 balance - 加 blocked - token 不变
     *
     * @param coinOrderVO 订单信息
     * @param walletVO    用户钱包
     */
    @Override
    public void doPayForTheOrder(CoinOrderVO coinOrderVO, FuUserWalletVO walletVO) {
        double coinNumber = coinOrderVO.getCoinNumber();
        Integer orderType = coinOrderVO.getType();
        // 支付订单
        walletVO.setBalance(coinNumber);
        walletVO.setAvailable(coinNumber);
        walletVO.setOrderType(orderType);
        this.walletService.doPayForTheOrder(walletVO);

        if (orderType == 1) {
            // 只有正在进行的项目才会正式支付
            this.doPayForTheOrderWhenProjectIsRelease(coinOrderVO);
        }

        // 订单支付成功
        this.updateCoinOrder(coinOrderVO);

        // 修改项目已筹代币数和认筹人数
        CoinUserProjectVO coinUserProjectVO = new CoinUserProjectVO();
        coinUserProjectVO.setId(coinOrderVO.getProjectId());
        /***** 购买的代币为整数个，这里将 double 转成了 long *****/
        coinUserProjectVO.setFundedAmount(Long.parseLong(String.valueOf((int)coinNumber)));
        coinUserProjectVO.setParticipantNumber(1L);
        this.projectService.doPayForTheOrder(coinUserProjectVO);
    }

    @Override
    public void deleteCoinOrder(CoinOrderVO coinOrderVO) {
        this.daoRouter.update("CoinOrder.deleteCoinOrder", coinOrderVO);
    }

    /**
     * 正在进行的项目
     * 支付之后将代币添加到用户的钱包中，并且处于锁定状态
     *
     * @param coinOrderVO
     */
    @Override
    public void doPayForTheOrderWhenProjectIsRelease(CoinOrderVO coinOrderVO) {
        Long userId = coinOrderVO.getUserId();
        Long projectId = coinOrderVO.getProjectId();
        Double tokenNumber = coinOrderVO.getTokenNumber();
        // 查询钱包中是否有该种代币
        Map<String, Object> params = new HashMap<>();
        params.put("id", projectId);
        params.put("dataStatus", 1);
        List<CoinUserProjectVO> coinUserProjectVOS = this.projectService.loadUserProject(params);
        Long tokenId = coinUserProjectVOS.get(0).getTokenId();

        FuUserWalletVO userWallet = this.walletService.getUserWallet(userId, tokenId);
        if (userWallet == null) {
            // 没有该币种的钱包记录,新建钱包，并增加锁定的代币
            FuUserWalletVO fuUserWalletVO = new FuUserWalletVO();
            fuUserWalletVO.setUserId(userId);
            fuUserWalletVO.setCoinId(tokenId);
            fuUserWalletVO.setBalance(0d);
            fuUserWalletVO.setBlocked(tokenNumber);
            fuUserWalletVO.setAvailable(0d);
            fuUserWalletVO.setCreatedBy(coinOrderVO.getModifiedBy());
            fuUserWalletVO.setCreatedDate(coinOrderVO.getCreatedDate());
            fuUserWalletVO.setDataStatus(1);
            this.walletService.insertFuUserWallet(fuUserWalletVO);
        } else {
            // 已经有了则增加锁定的数量
            userWallet.setBlocked(tokenNumber);
            userWallet.setModifiedBy(coinOrderVO.getModifiedBy());
            userWallet.setModifiedDate(coinOrderVO.getCreatedDate());
            this.walletService.doIncreaseBlocked(userWallet);
        }
    }

    @Autowired
    private ICoinProjectService projectService;
    @Autowired
    private ICoinTokenService tokenService;
    @Autowired
    private IFuUserWalletService walletService;
    @Autowired
    private IDaoRouter daoRouter;

}